<?php

namespace app\order\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\api\logic\ApiOrderLogic;
use app\api\logic\ApiOrdercheckLogic;
use app\api\logic\FreightLogic;
use app\api\logic\FeiShuTalkLogic;
use app\order\logic\OrderSourceLogic;
use app\order\logic\CheckbillLogic;
use app\api\logic\ShopyLogic;
use app\order\logic\OrderReportSkuLogic;
use app\api\logic\FeiShuMessageLogic;
use app\data\util\HttpUtil;
use app\api\logic\CheckLogic;
use app\purchase\logic\PlanSuggestLogic;

class OrderRefundLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\order\model\Order();
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $shop_id = $params['shop_id'] ?? "";
        $order_id = $params['order_id'] ?? "";
        $financial_status = $params['financial_status'] ?? "";
        $fulfillment_status = $params['fulfillment_status'] ?? "";
        $LogisticsStatus = $params['LogisticsStatus'] ?? "";
        $createtime = $params['createtime'] ?? "";

        $where = [];
        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }
        if (!empty($order_id)) {
            $order_ids = explode("\n", trim($order_id));
            $order_ids_new = array_map('trim', array_filter($order_ids, function($v) {  
                return !empty(trim($v));  
            }));
            if (!empty($order_ids_new)) {
                $where[] = ['order_id|name', 'in', $order_ids_new];
            }
        }
        if (!empty($fulfillment_status)) {
            $where[] = ['fulfillment_status', '=', $fulfillment_status];
        }
        if (!empty($financial_status)) {
            $where[] = ['financial_status', '=', $financial_status];
        }
        if ($LogisticsStatus){
            $where[] = ['LogisticsStatus', '=', $LogisticsStatus];
        }

        if($createtime){
            $where[]     = ['createtime', '>=', strtotime($createtime['0'])];
            $where[]     = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }

        $where[]  = ['financial_status', 'in', ["refunded", "partially_refunded"]];
        $list = Db::name('order_achievement')
            ->where($where)
            ->order('createtime desc')
            ->paginate($limit);
        $lists = $list->items();
        $order_ids = array_column($lists,'order_id');
        //批量获取店铺信息;
        $shop_list     = Db::name('shops')->field('id as shop_id,name')->select()->toArray();
        $shop_list_map = array_column($shop_list,null,'shop_id');
        
        foreach ($lists as $k=>$v) {
            $shop_info = $shop_list_map[$v['shop_id']]??[];
            $lists[$k]['createtime'] = date('Y-m-d H:i', $v['createtime']);
            
            $lists[$k]['shop_name'] = $shop_info['name']??'';
        }
        
        $data = [
            'list'  => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单编号', 'order_id'];
        $header[] = ['支付金额', 'total_price'];
        $header[] = ['支付渠道', 'payment_gateway_names'];
        $header[] = ['支付状态', 'financial_status'];
        $header[] = ['发货状态', 'fulfillment_status'];
        $header[] = ['订单创建时间', 'createtime'];
        $header[] = ['物流单号', 'tracking_number'];
        
        $tableName = $this->model->getName();

        
        $shop_id = $params['shop_id'] ?? "";
        $order_id = $params['order_id'] ?? "";
        $financial_status = $params['financial_status'] ?? "";
        $fulfillment_status = $params['fulfillment_status'] ?? "";
        $LogisticsStatus = $params['LogisticsStatus'] ?? "";
        $createtime = $params['createtime'] ?? "";

        $where = [];
        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }
        if (!empty($order_id)) {
            $order_ids = explode("\n", trim($order_id));
            $order_ids_new = array_map('trim', array_filter($order_ids, function($v) {  
                return !empty(trim($v));  
            }));
            if (!empty($order_ids_new)) {
                $where[] = ['order_id|name', 'in', $order_ids_new];
            }
        }
        if (!empty($fulfillment_status)) {
            $where[] = ['fulfillment_status', '=', $fulfillment_status];
        }
        if (!empty($financial_status)) {
            $where[] = ['financial_status', '=', $financial_status];
        }
        if ($LogisticsStatus){
            $where[] = ['LogisticsStatus', '=', $LogisticsStatus];
        }

        if($createtime){
            $where[]     = ['createtime', '>=', strtotime($createtime['0'])];
            $where[]     = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }

        $where[]  = ['financial_status', 'in', ["refunded", "partially_refunded"]];
        $lists = Db::name('order_achievement')
            ->where($where)
            ->order('createtime desc')
            ->select()->toarray();
            
        //批量获取店铺信息;
        $shop_list     = Db::name('shops')->field('id as shop_id,name')->select()->toArray();
        $shop_list_map = array_column($shop_list,null,'shop_id');
        
        foreach ($lists as $k=>$v) {
            $shop_info = $shop_list_map[$v['shop_id']]??[];
            $lists[$k]['createtime'] = date('Y-m-d H:i', $v['createtime']);
            $lists[$k]['shop_name'] = $shop_info['name']??'';
        }

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    

    /**
    * @desc    StoreRefundRate店铺争议率
    * @date    2025/7/16
    * @author  zhangheng
    */
    public function StoreRefundRate($params = [])
    {
        $shops = Db::name('shops')
            ->field('id as shop_id,name as shop_name')
            ->where('status',1)
            ->select()
            ->toarray();
        $shop_map = array_column($shops,'shop_name','shop_id');

        $shop_id       = $params['shop_id'] ?? [];
        $createtime    = $params['createtime'] ?? [];
        // $createtime    = $params['createtime'] ?? ["2025-05-01","2025-05-31"];
        if (empty($shop_id)) {
            // return json(DefaultResponse(200, true, '获取成功', []));
            return json(DefaultResponse(201, false, '请选择店铺'));
        }
        if (empty($createtime)) {
            return json(DefaultResponse(201, false, '请选择订单付款时间'));
        }

        $where = [];
        $where[]  = ['shop_id', 'in', $shop_id]; 
        $where[] = ['createtime', '>=', strtotime($createtime['0'])];
        $where[] = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        $where2 = [];
        $where2[]  = ['financial_status', 'in', ["refunded", "partially_refunded"]];

        $Dimension       = $params['Dimension'] ?? 1;
        if($Dimension == 1){
            $list = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") as date,
                COUNT(id) as quantity,shop_id')
                ->group('date,shop_id') 
                ->where($where)
                ->order(['date' => 'asc','quantity' => 'desc'])
                ->select()
                ->toArray();
            $list2 = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") as date,
                COUNT(id) as dispute,shop_id')
                ->group('date,shop_id')   
                ->where($where)
                ->where($where2)
                ->order(['date' => 'asc','dispute' => 'desc'])
                ->select()  
                ->toArray();
        }
        if($Dimension == 2){
            $list = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%u") as date,
                COUNT(id) as quantity,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->order(['date' => 'asc','quantity' => 'desc'])
                ->select()  
                ->toArray();
            $list2 = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%u") as date,
                COUNT(id) as dispute,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->where($where2)
                ->order(['date' => 'asc','dispute' => 'desc'])
                ->select()  
                ->toArray();
        }
        if($Dimension == 3){
            $list = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m") as date,
                COUNT(id) as quantity,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->order(['date' => 'asc','quantity' => 'desc'])
                ->select()  
                ->toArray();
            $list2 = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m") as date,
                COUNT(id) as dispute,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->where($where2)
                ->order(['date' => 'asc','dispute' => 'desc'])
                ->select()  
                ->toArray();
        }
        // halt($list);
        $list_new = [];
        try { 
            $list_new = array_map(function($item) use ($list2,$shop_map,$Dimension) {
                $item['dispute'] = 0;
                foreach ($list2 as $item2) {
                    $item['DisputeRate'] = 0;
                    if ($item['date'] == $item2['date']) {
                        $item['dispute'] = $item2['dispute'];
                        if($item['dispute'] > 0){
                            $item['DisputeRate'] = number_format($item['dispute']/$item['quantity']*10000,0);
                            break;
                        }
                    }
                }
                
                if($Dimension == 2){
                    $item['date'] = str_replace('-','年',$item['date']);
                    $item['date'] = $item['date'].'周';
                }
                $item_new = [
                    'info' => "额外信息1额外信息1额外信息1额外信息1额外信息1额外信息1",
                    'shop' => "店铺:".$shop_map[$item['shop_id']],
                    'date' => $item['date'],
                    'quantity' => (int)$item['DisputeRate'] ?? 0,
                ];
                return $item_new;
            }, $list);
        } catch (\Exception $e) {
            $list_new = [];
        }
        return json(DefaultResponse(200, true, '获取成功', $list_new));
    }

}
